package cn.monkey.transport.netty;

import cn.monkey.transport.core.DelegatesExchange;
import cn.monkey.transport.core.Exchange;
import io.netty.channel.Channel;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class SimpleNettyExchangeFactory implements NettyExchangeFactory<NettyExchange> {
    @Override
    public NettyExchange apply(String key, Exchange exchange, Channel channel) {
        if (exchange == null) {
            return new SimpleNettyExchange(key, channel).bind();
        }
        if (exchange instanceof NettyExchange nettyExchange) {
            return new SimpleNettyDelegatesExchange(key, List.of(new SimpleNettyExchange(key, channel).bind(), nettyExchange));
        }
        if (exchange instanceof DelegatesExchange delegatesExchange) {
            Set<NettyExchange> nettyExchanges = new HashSet<>();
            for (Exchange e : delegatesExchange.delegates()) {
                if (e instanceof NettyExchange nettyExchange) {
                    nettyExchanges.add(nettyExchange);
                    continue;
                }
                throw new IllegalArgumentException("exchange should be NettyExchange type");
            }
            nettyExchanges.add(new SimpleNettyExchange(key, channel).bind());
            return new SimpleNettyDelegatesExchange(key, nettyExchanges);
        }
        throw new IllegalArgumentException("exchange should be NettyExchange type or null");
    }
}
